const requestUrl = ''

function request (url, data = {}, method, loading = true) {
  if (loading) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestUrl + url,
      data,
      method,
      timeout: 6000,
      success: (result) => {
        if (loading) wx.hideLoading()
        if (result.statusCode === 200) {
          resolve(result.data)
        } else {
          wx.showToast({
            title: result.errMsg,
            icon: 'error'
          })
          reject(result)
        }
      },
      fail: (res) => {
        // 网络错误或服务器错误都会走这里
        if (loading) wx.hideLoading()
        wx.showToast({
          title: '抱歉服务器繁忙',
          icon: 'error'
        })
        reject(res)
      },
      complete: (res) => {
        // if (loading) wx.hideLoading()
        // console.log(res)
      },
    })
  })
}

function RequestPost (url, data, loading) {
  return request(url, data, 'post', loading)
}

function RequestGet (url, data, loading) {
  return request(url, data, 'get', loading)
}

module.exports = {
  RequestPost,
  RequestGet
}
